/*
 * @Author: Aaron
 * @Date: 2022-04-26 12:42:34
 * @LastEditors: Aaron Huang
 * @LastEditTime: 2022-10-25 18:42:45
 * @Description: file content
 * @FilePath: \ias_ui\src\permission.js
 * @Company: 沃尔玛
 */
import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import './styles/nprogress.css'
import { MessageBox } from 'element-ui'
import { getUser, getToken } from './utils/localStore'
import { toPortal } from '@/api/SignUtil'
import { decrypt } from './utils/aesEdit'
import store from './store'
import { getVersion } from '@/api/versionControl'
import versionRecord from '../public/static/versionRecord'

const versionControl = async () => {
  try {
    const v = await getVersion()
    if (v === versionRecord) return
    MessageBox.alert('当前应用已更新，即将为你重新加载...', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    }).then(() => {
      window.location.reload()
    })
  } catch (error) {
    console.log(error)
  }
}

const getAuthorities = (to, from, next) => {
  delete to.query.code
  delete to.query.c2
  delete to.query.c3
  delete to.query.launch
  delete to.query.appId
  return store
    .dispatch('findAuthorities')
    .then(async (res) => {
      const hasRoles = store.getters.rolesTable && store.getters.rolesTable.length > 0
      if (hasRoles) {
        next()
        versionControl()
      } else {
        const rolesTable = store.getters.roles.map((item) => {
          return item.ruleCode
        })
        const accessRoutes = await store.dispatch('generateRoutes', rolesTable)
        // router.addRoutes(accessRoutes)
        router.selfaddRoutes(accessRoutes)
        next({ ...to, replace: true })
      }
    })
    .catch((err) => {
      console.log(err)
      store
        .dispatch('FedLogOut')
        .then(() => {
          toPortal()
          NProgress.done()
          // next({ path: '/' })
        })
        .catch((err) => console.log(err))
    })
}

// 路由拦截
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  let tokenPortal = to.query.code

  tokenPortal = !tokenPortal ? '' : decrypt(tokenPortal.replace(/\s+/g, '+'))
  if (tokenPortal && tokenPortal !== getToken()) {
    // portal页跳转，通过token登录
    store.dispatch('loginByToken', tokenPortal).then(() => {
      getAuthorities(to, from, next)
    }).catch(() => {
      window.setTimeout(() => {
        router.go(-1)
      }, 2000)
    })
  } else {
    if (getUser()) {
      getAuthorities(to, from, next)
    } else {
      toPortal()
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
